// 封装axios
import axios from "axios";
import { Message } from "element-ui";

// 创建实例
const service = axios.create({
    baseURL: "",
    timeout: 5000,
    withCredentials: true // 启用Cookie支持
})

// 请求拦截
service.interceptors.request.use(conf => {
    if (process.env.NODE_ENV !== 'production') {
        console.debug('[REQ]', conf.method?.toUpperCase(), conf.baseURL + conf.url, conf.data || conf.params);
    }
    
    // 如果localStorage中有token，添加到请求头
    const token = localStorage.getItem('token');
    if (token) {
        conf.headers.Authorization = `Bearer ${token}`;
    }
    
    return conf
})

// 响应拦截
service.interceptors.response.use(conf => {
    if (process.env.NODE_ENV !== 'production') {
        console.debug('[RES]', conf.config.url, conf.status, conf.data);
    }
    
    // 如果响应中有token，保存到localStorage
    if (conf.data && conf.data.data && conf.data.data.token) {
        localStorage.setItem('token', conf.data.data.token);
    }
    
    return conf.data
}, err => {
    // 如果是401未授权，清除token并跳转到登录页
    if (err.response && err.response.status === 401) {
        localStorage.removeItem('token');
        // 如果不在登录页，跳转到登录页
        if (window.location.pathname !== '/login') {
            window.location.href = '/login';
        }
    }
    
    Message({
        type: "error",
        message: err.response ? (err.response.data.message || '网络错误') : "网络错误"
    })
    return Promise.reject(err);
})

export default service